<?php
/**
 * 微信支付
 * @author chenlisong E-mail:chenlisong1021@163.com 
 * @version 创建时间：2016年8月30日 下午5:04:38 
 * 类说明
 */
class WxpayAction extends BaseAction{
	
	public function _initialize(){
		header('Content-Type:application/json; charset=utf-8');
		$this->param = $_REQUEST;
	}
	
	public function index(){
		echo $this->err("非法操作！");
	}
	
	/**
	 * 支付订单
	 */
	public function wxpayOrder(){
		$Order = M('Order');$OrderDetails = M('OrderDetails');$Product = M('Product');$ShopProduct = M("ShopProduct");$ShopAttributeValues = M("ShopAttributeValues");
		$param = $this->param;
		if(empty($param['orderCode'])){
			echo $this->err("参数错误！");
			return ;
		}
		//判断订单状态是否正确
		$where['code'] = $param['orderCode'];
		$where['flag'] = 1;
		$where['status'] = 1;
		$info = $Order->where($where)->find();
		if(count($info) == 0){
			echo $this->err("错误的订单状态，请重新下单！");
			return ;
		}
		//封装body
		$map['order_code'] = $param['orderCode'];
		$map['flag'] = 1;
		$goodslist = $OrderDetails->where($map)->field('product_id,name,num,attribute_values')->select();
		$body = '';
		foreach ($goodslist as $key=>$val){
			$productInfo = $Product->field('name,num,is_on')->where(array('id' => $val['product_id'], 'flag' => 1))->find();
			$shopProductInfo = $ShopProduct->field("num")->where(array('product_id' => $val['product_id'], 'flag' => 1,'shop_id'=>$info['shop_id']))->find();
			$sellNum = $val['num'];
			if ($val['attribute_values'] != "") {
				$attr_value_arr = explode(':', $val['attribute_values']);
				$attr_value_name = $attr_value_arr[1];
				$attribute_values = $ShopAttributeValues->where(array("product_id" => $val['product_id'], 'attr_value_name' => $attr_value_name,'shop_id'=>$info['shop_id']))->find();
				if ($attribute_values) {
					if ($sellNum > $attribute_values['num']) {
						echo $this->err($val['name'] . $attr_value_name.'库存不足，请重新选择商品！');
						return;
					}
				}
			} else {
				if ($sellNum > $shopProductInfo['num']) {
					echo $this->err($val['name'] . '剩余'.$shopProductInfo['num'].'个,库存不足，请重新选择商品！');
					return;
				}
			}
			//商品下架
			if ($productInfo['is_on'] == 2) {
				echo $this->err($val['name'] . '已下架，请重新选择商品！');
				return;
			}
			$body .= $val['name'].$val['num']."份.";
		}
		$name = '佳好友--网络订单，单号：'.$param['orderCode'];
		$url = C('WEIXIN_PAY_NOTIFY_URL');//回调地址
		//组装数据
		import('COM.Core.WxpayAppUtils');
		$WxpayUntils = new WxpayAppUtils();
		$postData["appid"] = C('WEIXIN_APPID');//公众账号ID
		$postData["mch_id"] = C('WEIXIN_MCHID');//商户号
		$postData["nonce_str"] = $WxpayUntils->createNoncestr();//随机字符串
		$postData['body'] = $name;
		$postData['out_trade_no'] = $param['orderCode'];
		$postData['total_fee'] = ($info['real_price'] + $info['mail_fee'] )* 100;
		$postData['notify_url'] = $url;
		$postData['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
		$postData['trade_type'] = "APP";
		$postData["sign"] = $WxpayUntils->getSign($postData);//签名
		$result = $WxpayUntils->getAppData($postData);
		if(!empty($result['prepay_id'])){
			$data['appid'] = $result['appid'];
			$data['partnerid'] = $result['mch_id'];
			$data['noncestr'] = $result['nonce_str'];
			$data['package'] = 'Sign=WXPay';
			$data['timestamp'] = time();
			$data['prepayid'] = $result['prepay_id'];
			$data['sign'] = $WxpayUntils->getSign($data);
			echo $this->suc($data);
		}else{
			echo $this->err("系统错误！");
		}
	}
	
	public function orderNotifyReturn(){
		import('COM.Core.WxpayAppUtils');
		$WxpayUntils = new WxpayAppUtils();
		//存储微信的回调
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];//接收XML回调参数，和$_POST差不多
		$parameter = $WxpayUntils->xmlToArray($xml);
		if(!empty($parameter['result_code']) && $parameter['result_code'] =='SUCCESS'){
			//处理订单
			$this->handleOrder($parameter);
			$returnData['return_code'] = "SUCCESS";
		}else{
			$returnData['return_code'] = "FAIL";
			$returnData['return_msg'] = "签名失败";
		}
		$returnXml = $WxpayUntils->arrayToXml($returnData);
		echo $returnXml;
    }
    
    /**
     * 处理订单
     */
    private function handleOrder($parameter){
    	//付款成功进行订单处理
    	$Order = M('Order');
		$Shop = M("Shop");$OrderDetails = M('OrderDetails');$Product = M('Product');$ShopProduct = M("ShopProduct");$ShopAttributeValues = M("ShopAttributeValues");
    	$code = $parameter['out_trade_no'];
    	$where['code'] = $code;
    	$info = $Order->where($where)->find();
    	if(in_array($info['status'], array(1,-1))){
			$Shopinfo = $Shop->where(array("id"=>$info['shop_id']))->field("user_id")->find();
			$this->insertNotice($Shopinfo['user_id'],"您有未处理的订单！",$info['code']);
    		//订单状态更改
    		$data['status'] = 2;
    		$data['flag'] = 1;
    		$data['pay_type'] = 2;
    		$data['pay_time'] = time();
    		$data['pay_code'] = $parameter['transaction_id'];
    		$data['pay_email'] = $parameter['openid'];
    		$data['update_time'] = time();
    		$Order->where($where)->save($data);
			//扣除库存
			$orderDetails = $OrderDetails->where(array('order_code'=>$info['code'],'flag'=>1))->select();
			//$querySql = 'SET num = CASE id ';
			//$queryIds = "";

			$querySql_s = 'SET num = CASE product_id ';
			$queryIds_s = "";

			$querySql_1 = 'SET num = CASE id ';
			$queryIds_1 = "";

			foreach ($orderDetails as $pk => $pv) {
				$sellNum = $pv['num'];
				//组装扣除商品数量sql
				if ($pv['attribute_values'] != "") {
					$querySql_1 .= ' WHEN ' . $pv['attr_values_id'] . ' THEN num -' . $sellNum . " ";
					$queryIds_1 .= $pv['attr_values_id'] . ",";
				} else {
					//$querySql .= ' WHEN ' . $pv['product_id'] . ' THEN num -' . $sellNum . " ";
					//$queryIds .= $pv['product_id'] . ",";
					$querySql_s .= ' WHEN ' . $pv['product_id'] . ' THEN num -' . $sellNum . " ";
					$queryIds_s .= $pv['product_id'] . ",";
				}

			}

			if ($queryIds_1 != '') {
				$querySql_1 .= ' END ';
				$queryIds_1 = substr($queryIds_1, 0, strlen($queryIds_1) - 1);
				$querySql_1 .= 'where id in (' . $queryIds_1 . ') and shop_id=' . $info['shop_id'];
			}
			/*
			if ($queryIds != '') {
				$querySql .= ' END ';
				$queryIds = substr($queryIds, 0, strlen($queryIds) - 1);
				$querySql .= 'where id in (' . $queryIds . ')';
			}
			*/

			if ($queryIds_s != '') {
				$querySql_s .= ' END ';
				$queryIds_s = substr($queryIds_s, 0, strlen($queryIds_s) - 1);
				$querySql_s .= 'where product_id in (' . $queryIds_s . ') and shop_id=' . $info['shop_id'];
			}

			//扣除商品表库存
			/*
			if ($queryIds != '') {
				$Product->execute('update __TABLE__ ' . $querySql);
			}
			*/
			//扣除店铺规格库存
			if ($queryIds_1 != '') {
				$ShopAttributeValues->execute('update __TABLE__ ' . $querySql_1);
			}
			//扣除店铺商品库存
			if ($queryIds_s != '') {
				$ShopProduct->execute('update __TABLE__ ' . $querySql_s);
			}
		}else{
    		$msg = "交易号为：".$_POST['transaction_id']."，订单编号为".$parameter['out_trade_no']."使用微信支付完成，但是订单状态为非正常状态！";
    		writeLog($msg);
    	}
    	return true;
    }
    
    /**
     * 微信充值
     */
    public function recharge(){
    	$RechargeSetting = M('RechargeSetting');$RechargeLog = M('RechargeLog');
    	$param = $this->param;
    	$where['flag'] = 1;
    	$where['id'] = $param['rechargeId'];
    	$info = $RechargeSetting->where($where)->find();
    	if(empty($info)){
    		echo $this->err("错误的充值金额！");
    		return;
    	}
    	$code = date('YmdHis').rand(10,99);
    	$regData['code'] = $code;
    	$regData['user_id'] = $param['userId'];
    	$regData['recharge_price'] = $info['recharge_price'];
    	$regData['give_price'] = $info['give_price'];
    	$regData['create_time'] = time();
    	$RechargeLog->add($regData);
    	$body = "在线充值".$info['recharge_price']."返利".$info['give_price'];
    	$name = '佳好友--在线充值';
    	$url = C('WEIXIN_PAY_RECHARGE_NOTIFY_URL');//回调地址
    	//组装数据
    	import('COM.Core.WxpayAppUtils');
    	$WxpayUntils = new WxpayAppUtils();
    	$postData["appid"] = C('WEIXIN_APPID');//公众账号ID
    	$postData["mch_id"] = C('WEIXIN_MCHID');//商户号
    	$postData["nonce_str"] = $WxpayUntils->createNoncestr();//随机字符串
    	$postData['body'] = $name;
    	$postData['out_trade_no'] = $code;
    	$postData['total_fee'] =  $info['recharge_price'] * 100;
    	$postData['notify_url'] = $url;
    	$postData['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
    	$postData['trade_type'] = "APP";
    	$postData["sign"] = $WxpayUntils->getSign($postData);//签名
    	$result = $WxpayUntils->getAppData($postData);
    	if(!empty($result['prepay_id'])){
    		$data['appid'] = $result['appid'];
    		$data['partnerid'] = $result['mch_id'];
    		$data['noncestr'] = $result['nonce_str'];
    		$data['package'] = 'Sign=WXPay';
    		$data['timestamp'] = time();
    		$data['prepayid'] = $result['prepay_id'];
    		$data['sign'] = $WxpayUntils->getSign($data);
    		echo $this->suc($data);
    	}else{
    		echo $this->err("系统错误！");
    	}
    }
    
    /**
     * 充值回调
     */
    public function rechargeNotifyReturn(){
    	import('COM.Core.WxpayAppUtils');
    	$WxpayUntils = new WxpayAppUtils();
    	//存储微信的回调
    	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];//接收XML回调参数，和$_POST差不多
    	$parameter = $WxpayUntils->xmlToArray($xml);
    	if(!empty($parameter['result_code']) && $parameter['result_code'] =='SUCCESS'){
    		//处理订单
    		$this->handleRecharge($parameter);
    		$returnData['return_code'] = "SUCCESS";
    	}else{
    		$returnData['return_code'] = "FAIL";
    		$returnData['return_msg'] = "签名失败";
    	}
    	$returnXml = $WxpayUntils->arrayToXml($returnData);
    	echo $returnXml;
    }
    
    /**
     * 处理订单
     */
    private function handleRecharge($parameter){
    	//付款成功进行订单处理
    	$RechargeLog = M('RechargeLog');$User = M('User');$UserDetails = M('UserDetails');$Fields = M('Fields');
    	$where['code'] = $parameter['out_trade_no'];
    	$info = $RechargeLog->where($where)->find();
    	$balance = (float) $User->where('id = '.$info['user_id'])->getField('balance');
    	if(in_array($info['status'], array(1,-1))){
    		//给用户加金额（含赠送）
    		$data[0]['user_id'] = $info['user_id'];
    		$data[0]['title'] = "微信充值";
    		$data[0]['type'] = 1;
    		$data[0]['price'] = $info['recharge_price'];
    		$data[0]['last_price'] = $balance;
    		$data[0]['create_time'] = time();
    		$data[1]['user_id'] = $info['user_id'];
    		$data[1]['title'] = "充值赠送";
    		$data[1]['type'] = 1;
    		$data[1]['price'] = $info['give_price'];
    		$data[1]['last_price'] = $balance + $info['recharge_price'];
    		$data[1]['create_time'] = time();
    		$UserDetails->addAll($data);
    		$User->where('id = '.$info['user_id'])->setInc('balance',($info['recharge_price'] + $info['give_price']));
    		//给推荐人分润
    		$parentId = $User->where('id = '.$info['user_id'])->getField('parent_id');
    		if(!empty($parentId)){
    			$bl = (float) $Fields->where('flag = 1 and field ="app_recharge_return_rate"')->getField('value');
    			$price = sprintf("%.2f",$info['recharge_price'] * $bl);
    			$udata['user_id'] = $parentId;
    			$udata['title'] = "充值返利";
    			$udata['type'] = 1;
    			$udata['price'] = $price;
    			$udata['from_user_id'] = $info['user_id'];
    			$udata['last_price'] = (float) $User->where('id = '.$parentId)->getField('balance');;
    			$udata['create_time'] = time();
    			$UserDetails->add($udata);
    			$User->where('id = '.$parentId)->setInc('balance',$price);
    		}
    		//订单状态更改
    		$dataOrder['status'] = 2;
	    	$dataOrder['flag'] = 1;
	    	$dataOrder['pay_type'] = 2;
	    	$dataOrder['pay_time'] = time();
	    	$dataOrder['pay_code'] = $parameter['transaction_id'];
	    	$dataOrder['pay_email'] = $parameter['openid'];
	    	$dataOrder['update_time'] = time();
    		$RechargeLog->where($where)->save($dataOrder);
    	}else{
    		$msg = "交易号为：".$_POST['transaction_id']."，订单编号为".$parameter['out_trade_no']."使用微信支付完成，但是订单状态为非正常状态！";
    		writeLog($msg);
    	}
    	return true;
    }


	/**
	 * 新增消息
	 * 新增商家待处理订单消息
	 */
	private function insertNotice($userId,$message,$ambulance){
		$Notice = M('Notice');$User = M('User');
		$jpushId = $User->where('id = '.$userId)->getField('jpush_id');
		if(!empty($jpushId)){
			$data['type'] = 4;
			$data['user_id'] = $userId;
			$data['message'] = $message;
			$data['ambulance'] = $ambulance;
			$data['create_time'] = time();
			$Notice->add($data);
		}
		return true;
	}
}